﻿using System;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using System.Web.UI.WebControls;
using JM.JCY.Proxy;
using JM.JCY.BusinessEntity;
using JM.JCY.Common;
using System.Data;
using JM.JCY.Common.Utilities;
using NCS.IConnect.ApplicationContexts;
using System.Web.UI;
using System.IO;
using System.Globalization;
using System.Collections.Generic;
using JM.JCY.BusinessEntity.DTOs.Notification;

namespace JM.JCY.SharePointComponent.Layouts.SharePointComponent
{
    public partial class ViewAllNotifications : LayoutsPageBase, ICallbackEventHandler
    {
        public int _staffId
        {
            set;
            get;
        }

        public string _errorMessage
        {
            set;
            get;
        }

        public bool _isValid
        {
            get;
            set;
        }

        public static int PAGESIZE = 10;
        public string pagerText = "0";
        public int pageNum
        {
            get
            {
                if (Session["Notif_p16a5mr6g1ve2tmk1q63163c4"] == null)
                {
                    return 0;
                }
                else
                {
                    return (int)Session["Notif_p16a5mr6g1ve2tmk1q63163c4"];
                }
            }
            set
            {
                Session["Notif_p16a5mr6g1ve2tmk1q63163c4"] = value;
            }
        }

        public int pageIndexNum
        {
            get
            {
                if (Session["Notif_pageIndexNump166g0asu1ve2tmk1q63163c4"] == null)
                {
                    return 0;
                }
                else
                {
                    return (int)Session["Notif_pageIndexNump166g0asu1ve2tmk1q63163c4"];
                }
            }
            set
            {
                Session["Notif_pageIndexNump166g0asu1ve2tmk1q63163c4"] = value;
            }
        }

        public NotificationDataSet.NotificationTableDataTable NotificationDt
        {
            get
            {
                if (Session["JCY_NotificationDt"] != null)
                {
                    return (NotificationDataSet.NotificationTableDataTable)Session["JCY_NotificationDt"];
                }
                else
                {
                    return new NotificationDataSet.NotificationTableDataTable();
                }
            }

            set
            {
                Session["JCY_NotificationDt"] = value;
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                _staffId = 11;
                if (ApplicationContext.Current.GetKeyValue("userId") != null)
                {
                    _staffId = Convert.ToInt32(ApplicationContext.Current.GetKeyValue("userId"));
                }

                string callbackReference = Page.ClientScript.GetCallbackEventReference(this, "arg", "ReceiveCallback", "context", false);
                string callbackScript = string.Format("function CallServer(arg,context){{ {0}  }}", callbackReference);
                Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "CallServer", callbackScript, true);

                if (Page.IsPostBack == false)
                {
                    if (Request.Params["Test"] != null)
                    {
                        InsertNotifications();
                    }
                    NotificationDataSet.NotificationTableDataTable dt = new NotificationDataSet.NotificationTableDataTable();
                    using (NotificationProxy proxy = new NotificationProxy())
                    {
                        dt = proxy.GetLastThirtyDaysNotifications(_staffId);
                        NotificationDt = dt;
                    }
                    BindNoti(1);
                }
            }
            catch (Exception ex)
            {
                bool isok = JCYUtility.ExceptionHandle("viewNotification", ex);
            }

        }

        protected void InsertNotifications()
        {
            IList<int> reciptid = new List<int>();

            for (int i = 0; i < 100; i++)
            {
                reciptid.Add(12);
            }

            MultipleNotifications multifications = new MultipleNotifications();

            multifications.SenderId = _staffId;
            multifications.ActualContent = string.Format("<a href=\"/mysite/MOHPages/staffprofile/StaffProfileDetails.aspx?staffid={0}\">{1}</a> 给你照片评论了.", _staffId, ApplicationContext.Current.UserName);
            multifications.DisplayContent = ApplicationContext.Current.UserName + "给你照片评论了.";
            multifications.RedirectUrl = "/_layouts/SharePointComponent/staraward/GiveAStar.aspx";
            multifications.IsRead = false;
            multifications.CreatedBy = _staffId;

            multifications.RecipientId = reciptid;

            SingleNotification notis = new SingleNotification();
            notis.SenderId = _staffId;
            notis.ActualContent = "you nominate a star to staffname a link.";
            notis.DisplayContent = "you nominate a star to staffname.";
            notis.RedirectUrl = "_layouts/SharePointComponent/staraward/GiveAStar.aspx";
            notis.IsRead = false;
            notis.CreatedBy = _staffId;
            notis.RecipientId = _staffId;
            using (NotificationProxy noticProxy = new NotificationProxy())
            {
                noticProxy.InsertNotifications(multifications);
                int idd = 0;
                foreach (int i in reciptid)
                {
                    notis.ActualContent = "你给 zu meng。。。。评论了。" + idd.ToString();
                    notis.DisplayContent = notis.ActualContent;
                    noticProxy.InsertNotification(notis);
                    idd += 1;
                }
                
            }
        }

        protected void BindNoti(int indexId)
        {
            int pages = (NotificationDt.Rows.Count % PAGESIZE == 0) ? NotificationDt.Rows.Count / PAGESIZE : (NotificationDt.Rows.Count / PAGESIZE) + 1;
            pageNum = pages;

            if (indexId > pages)
            {
                indexId = pages;
            }
            else if (indexId < 1)
            {
                indexId = 1;
            }

            int startId = (indexId - 1) * PAGESIZE;
            int endId = indexId * PAGESIZE - 1;

            DataRow[] rows = NotificationDt.Select(string.Format("id>={0} and id<={1}", startId, endId));
            gvNotification.DataSource = rows;
            gvNotification.DataBind();
            pagerText = Common.JCYUtility.RenderPager(indexId, pageNum);
            HiddenFieldPagerText.Value = pagerText;
            HiddenFieldPageNum.Value = pageNum.ToString();
        }

        protected void gvNotification_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.Header)
            {
                //CheckBoxReadAll
                CheckBox CheckBoxReadAll = (CheckBox)e.Row.FindControl("CheckBoxReadAll");
                CheckBoxReadAll.Attributes.Add("onclick", "ReadAll()");
            }
                if (e.Row.RowType == DataControlRowType.DataRow)
            {
                NotificationDataSet.NotificationTableRow drv = (NotificationDataSet.NotificationTableRow)e.Row.DataItem;
                Label lbContent = (Label)e.Row.FindControl("lbContent");
                Label lbStatus = (Label)e.Row.FindControl("lbStatus");
                CheckBox CheckBoxRead = (CheckBox)e.Row.FindControl("CheckBoxRead");
                lbContent.Text = drv.ActualContent.ToString();
                if (drv.IsRead)
                {
                    lbStatus.Text = "已读";
                    CheckBoxRead.Visible = false;
                }
                else
                {
                    lbStatus.Text = "未读";
                    CheckBoxRead.Attributes.Add("onclick", "selected(" + drv.NotificationId + ",this)");
                }
            }
        }

        public string GetCallbackResult()
        {
            if (_isValid)
            {
                StringWriter writer1 = new StringWriter(CultureInfo.InvariantCulture);
                HtmlTextWriter writer2 = new HtmlTextWriter(writer1);

                gvNotification.RenderControl(writer2);
                writer2.Flush();
                writer2.Close();
                
                return writer1.ToString() + "|ox|" + pageNum + "|ox|" + pagerText;
            }
            else
            {
                return _errorMessage;
            }
        }

        public void RaiseCallbackEvent(string eventArgument)
        {
            try
            {
                _isValid = true;
                if (eventArgument.IndexOf("SetAsRead") > -1)
                {
                    string[] ps = eventArgument.Split(new char[] { '/' });
                    string[] psHeader = ps[0].Split(new char[] { '_' });
                    pageIndexNum = Convert.ToInt32(psHeader[1]);
                    int[] notificationIds = new int[ps.Length - 1];
                    for (int i = 1; i < ps.Length; i++)
                    {
                        notificationIds[i - 1] = Convert.ToInt32(ps[i]);
                        NotificationDt.FindByNotificationId(Convert.ToInt32(ps[i])).IsRead = true;
                    }

                    using (NotificationProxy proxy = new NotificationProxy())
                    {
                        proxy.MarkAsRead(notificationIds);
                    }

                    BindNoti(pageIndexNum);
                }
                else
                {
                    pageIndexNum = Convert.ToInt32(eventArgument);
                    BindNoti(pageIndexNum);
                }
            }
            catch (Exception ex)
            {
                _isValid = false;
                _errorMessage = ex.Message;
            }
        }
    }
}
